﻿using B.S.Data.MES.API.Applications.QualityManagement.ExamineMaterialsCommand.Commands;
using B.S.Domain.BasicData.QualityManagement;
using B.S.Infratrctrue;
using B.S.Requst;
using MediatR;

namespace B.S.Data.MES.API.Applications.QualityManagement.ExamineMaterialsCommand.CommandHandlers
{
    public class GetExamineMaterisonlCommandHandler : IRequestHandler<GetExamineMaterisonlCommand, APIRequst<APIPageing<List<MaterialsExamine>>>>
    {

        private readonly IBaseRepository<MaterialsExamine> _examinemasterRepository;
        public GetExamineMaterisonlCommandHandler(IBaseRepository<MaterialsExamine> examinemasterRepository)
        {
            _examinemasterRepository = examinemasterRepository;
        }
        public Task<APIRequst<APIPageing<List<MaterialsExamine>>>> Handle(GetExamineMaterisonlCommand request, CancellationToken cancellationToken)
        {
            APIRequst<APIPageing<List<MaterialsExamine>>> result = new APIRequst<APIPageing<List<MaterialsExamine>>>();
            result.Code = RequstCode.成功;
            result.Msg = RequstCode.成功.ToString();

            var list = _examinemasterRepository.GetAll().Where(x => !x.isDel);

            if (!string.IsNullOrEmpty(request.MaterialNo))
            {
                list = list.Where(x => x.MaterialNo == request.MaterialNo);
            }

            int recordcount = list.Count();
            int pagecount = (int)Math.Ceiling(recordcount * 1.0 / request.PageSize);

            list = list.OrderByDescending(x => x.MaterialsId).Skip((request.PageIndex - 1) * request.PageSize).Take(request.PageSize);

            APIPageing<List<MaterialsExamine>> paing = new APIPageing<List<MaterialsExamine>>();
            paing.TotalCount = recordcount;
            paing.Total = pagecount;
            paing.Data = list.ToList();
            result.Data = paing;

            return Task.FromResult(result);
        }
    }
}
